/*
 * ENCODER.c
 *
 * Created: 19-06-2013 13:30:41
 *  Author: Karmu
 */ 
#include <avr/io.h>
#include "ENCODER.h"

//define macros to check status
#define ENC_LFT_A !((1<<ENCODER_LEFT_A)&ENCODER_PIN)
#define ENC_LFT_B !((1<<ENCODER_LEFT_B)&ENCODER_PIN)

#define ENC_RGT_A !((1<<ENCODER_RIGHT_A)&ENCODER_PIN)
#define ENC_RGT_B !((1<<ENCODER_RIGHT_B)&ENCODER_PIN)

static uint8_t direction_status_left = 0;
static uint8_t direction_status_right = 0;

static int16_t counter_left = 0;
static int16_t counter_right = 0;

static uint8_t wait_left=0;
static uint8_t wait_right=0;

void encoder_init()
{
	ENCODER_DDR &= ~(_BV(ENCODER_LEFT_A) | _BV(ENCODER_RIGHT_A) | _BV(ENCODER_LEFT_B) | _BV(ENCODER_RIGHT_B));	/* Pin as input */
	ENCODER_PORT |=  _BV(ENCODER_LEFT_A) | _BV(ENCODER_RIGHT_A) | _BV(ENCODER_LEFT_B) | _BV(ENCODER_RIGHT_B);	/* Enable internal pull-up */
}

void encoder_left_check_status(void)
{
	//reading rotary and button
	//check if rotation is CLOCKWISE
	if(ENC_LFT_A & (!wait_left))
		wait_left=1;
	if (ENC_LFT_B & ENC_LFT_A & (wait_left))
	{
		direction_status_left=1;
		counter_left++;
		wait_left=2;
	}
	else if(ENC_LFT_A & (!ENC_LFT_B) & wait_left)
	{
		direction_status_left=2;
		counter_left--;
		wait_left=2;
	}
	if ((!ENC_LFT_A)&!(ENC_LFT_B)&(wait_left==2))
		wait_left=0;
}


void encoder_right_check_status(void)
{
	//reading rotary and button
	//check if rotation is CLOCKWISE
	if(ENC_RGT_A & (!wait_right))
	wait_right=1;
	if (ENC_RGT_B & ENC_RGT_A & (wait_right))
	{
		direction_status_right=2;
		counter_right--;
		wait_right=2;
	}
	else if(ENC_RGT_A & (!ENC_RGT_B) & wait_right)
	{
		direction_status_right=1;
		counter_right++;
		wait_right=2;
	}
	if ((!ENC_RGT_A)&!(ENC_RGT_B)&(wait_right==2))
	wait_right=0;
}

uint8_t encoder_left_get_status(void)
{
	return direction_status_left;
}

void encoder_left_reset_status(void)
{
	direction_status_left=0;
}

int16_t encoder_left_get_count(void)
{
	return counter_left;
}

void encoder_left_reset_count(void)
{
	counter_left=0;
}

uint8_t encoder_right_get_status(void)
{
	return direction_status_right;
}

void encoder_right_reset_status(void)
{
	direction_status_right=0;
}

int16_t encoder_right_get_count(void)
{
	return counter_right;
}

void encoder_right_reset_count(void)
{
	counter_right=0;
}